package com.schoolvisitors.service;

import com.schoolvisitors.entity.SystemConfig;
import com.schoolvisitors.exception.BusinessException;
import com.schoolvisitors.repository.SystemConfigRepository;
import com.schoolvisitors.response.ResultCode;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class SystemConfigService{
    private final SystemConfigRepository systemConfigRepository;
    private final Map<String, String> systemConfigMap = new HashMap<>();
    @Getter
    private Long systemConfigVersion = 0L;
    public SystemConfigService(SystemConfigRepository systemConfigRepository) {
        this.systemConfigRepository = systemConfigRepository;
    }

    public String getSystemConfigToString(String key) {
        if (systemConfigMap.containsKey(key)) {
            return systemConfigMap.get(key);
        }
        SystemConfig systemConfig = systemConfigRepository.findByConfigKey(key);
        if (systemConfig == null) {
            throw new RuntimeException("SystemConfig不存在:" + key);
        }
        String value = systemConfig.getConfigValue();
        systemConfigMap.put(key, value);
        return value;
    }

    public Integer getIntSystemConfigToInteger(String key) {
        String value = getSystemConfigToString(key);
        return Integer.valueOf(value);
    }

    public Long getSystemConfigToLong(String key) {
        String value = getSystemConfigToString(key);
        return Long.valueOf(value);
    }
    public Double getIntSystemConfigToDouble(String key) {
        String value = getSystemConfigToString(key);
        return Double.valueOf(value);
    }
    public Boolean getIntSystemConfigToBoolean(String key) {
        String value = getSystemConfigToString(key);
        return Boolean.valueOf(value);
    }


    public List<SystemConfig> getSystemConfigs() {
        return systemConfigRepository.findAll();
    }


    public void updateSystemConfig(String key, String value) {
        systemConfigVersion = System.currentTimeMillis();
        SystemConfig systemConfig = systemConfigRepository.findByConfigKey(key);
        if (systemConfig == null) {
            throw new BusinessException(ResultCode.SYSTEM_CONFIG_NOT_FOUNT);
        }
        systemConfig.setConfigValue(value);
//        switch (key){
//            case "name":
//
//        }
        systemConfigRepository.save(systemConfig);

        systemConfigMap.put(key, value);
    }

}
